package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.tanhua.commons.templates.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.vo.ContractVo;
import com.tanhua.domain.vo.MessageLikeVo;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.UserInfoVo;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class IMService {

    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private QuestionApi questionApi;
    @Reference
    private FriendApi friendApi;
    @Reference
    private CommentApi commentApi;

    /**
     * 接口名称：回复陌生人问题
     * @param userId 回复的陌生人用户id
     * @param reply 回复内容
     * @return
     */
    public ResponseEntity<Object> replyQuestions(Integer userId, String reply) {
        //1. 根据登陆用户id查询
        UserInfo userInfo = userInfoApi.findById(UserHolder.getUserId());
        //2. 查询陌生人问题
        Question question = questionApi.findByUserId(userId.longValue());

        //3. 发送的消息格式：{"userId": "","nickname":"","strangerQuestion": "？","reply": ""}
        Map<String,Object> map = new HashMap<>();
        map.put("userId",userInfo.getId());
        map.put("huanXinId",userInfo.getId());
        map.put("nickname",userInfo.getNickname());
        map.put("strangerQuestion",question!=null?question.getTxt():"你喜欢什么？");
        map.put("reply",reply);
        //4. 对象转json
        String mapString = JSON.toJSONString(map);
        //5. 发送消息
        huanXinTemplate.sendMsg(userId.toString(),mapString);
        return ResponseEntity.ok(null);
    }

    /**
     * 接口名称：联系人添加
     * @param friendId 好友
     * @return
     */
    public ResponseEntity<Object> addContacts(Long friendId) {
        //1. 当前登陆用户id
        Long userId = UserHolder.getUserId();
        //2. 保存好友关系到mongo中的tanhua_users表（双向）
        friendApi.save(userId,friendId);
        //3. 注册好友关系到环信
        huanXinTemplate.contactUsers(userId,friendId);
        return ResponseEntity.ok(null);
    }

    /**
     * 接口名称：联系人列表
     */
    public ResponseEntity<Object> contactsList(Integer page, Integer pagesize, String keyword) {
        // 获取登陆用户
        Long userId = UserHolder.getUserId();
        // 根据用户id查询联系人 db.tanhua_users.find({userId:1}).sort({created:-1})
        PageResult pageResult = friendApi.contactsList(page,pagesize,keyword,userId);
        // 获取查询的当前页数据
        List<Friend> friendList = (List<Friend>) pageResult.getItems();
        // 返回的vo集合
        List<ContractVo> voList = new ArrayList<>();
        // 封装voList
        if (!CollectionUtils.isEmpty(friendList)) {
            for (Friend friend : friendList) {
                ContractVo vo = new ContractVo();
                // 根据好友id查询
                UserInfo userInfo = userInfoApi.findById(friend.getFriendId());
                // 封装用户信息
                BeanUtils.copyProperties(userInfo,vo);
                // 设置id（好友id）
                vo.setUserId(friend.getFriendId().toString());
                // 获取城市
                vo.setCity(StringUtils.substringBefore(userInfo.getCity(),"-"));
                // 添加到集合
                voList.add(vo);
            }
        }
        // 设置voList到分页对象
        pageResult.setItems(voList);
        return ResponseEntity.ok(pageResult);
    }




    /**
     * 点赞评论喜欢列表
     * @param commentType 评论类型，1-点赞，2-评论，3-喜欢
     * @param page 当前页
     * @param pagesize 页大小
     * @return 通过MessageLikeVo封装返回结果并返回
     */


    public ResponseEntity<Object> querylikesList(
            Integer commentType, Integer page, Integer pagesize) {
        //1. 查询当前登陆用户相关的评论；【当前用户不是评论人，是被评论人；被评论人其实就是发布者】
        PageResult pageResult =
                commentApi.findCommentsByUserId(UserHolder.getUserId(),commentType,page,pagesize);
        //2. 获取评论数据
        List<Comment> commentList = (List<Comment>) pageResult.getItems();
        //3. 构造返回的结果数据
        List<MessageLikeVo> result = new ArrayList<>();
        //4. 遍历查询的评论数据，封装返回结果
        if (commentList != null && commentList.size()>0) {
            commentList.forEach((comment -> {
                MessageLikeVo messageLikeVo = new MessageLikeVo();
                // 根据评论人用户id查询
                UserInfo userInfo = userInfoApi.findById(comment.getUserId());
                BeanUtils.copyProperties(userInfo,messageLikeVo);
                messageLikeVo.setId(comment.getId().toHexString());
                String createDate = new SimpleDateFormat("yyyy-MM-dd").format(userInfo.getCreated());
                messageLikeVo.setCreateDate(createDate);
                result.add(messageLikeVo);
            }));
        } //5. 设置集合到分页对象中
        pageResult.setItems(result);
        return ResponseEntity.ok(pageResult);
    }














}
